<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>websocket</title>
</head>
<body>
	<h1>websocket客户端示例</h1>
	<div id="message"></div>
	<p>请输入一些文字</p>
	<input type="text" id="text">
	<button id="connect" onclick="connect();">建立连接</button>
	<button id="send" onclick="send();">发送数据</button>
	<button id="disconnect" onclick="disconnect();">断开连接</button>
	<script>
		var webSocket;
		var message = document.getElementById("message");
		
		function connect() {
			try{
				var readyState = new Array("正在连接","已建立连接","正在关闭连接","已经关闭连接");
				var host = "ws://lcoalhost:8000";
				webSocket = new webSocket(host);
				
				message.innerHTML = "<p>socket状态:" + readyState[webSocket.readyState] + "</p>";
				webSocket.onopen = function() {
					message.innerHTML +="<p>socket状态:" + readyState[webSocket.readyState] + "</p>";
				}
				webSocket.onmessage = function(msg) {
					message.innerHTML += "<p>接手消息:" + meg.data + "</p>";
				}
				webSocket.onclose = function() {
					message.innerHTML +="<p>socket状态:" + readyState[webSocket.readyState] + "</p>";
				}
			} catch(exception) {
				message.innerHTML += "<p>有错误发生</p>";
			}
			function send() {
				var text = document.getElementById("text").value;
				var message = document.getElementById("message");
				if(text == "") {
					message.innerHTML += "<p>请输入一些文字</p>";
					return;
				}
				try{
					webSocket.send(text);
					message.innerHTML += "<p>发送数据:" + text + "</p>";
				}
				catch (exception){
					message.innerHTML += "<p>发送数据错误</p>";
				}
				document.getElementById("text").value = ""
			}
			function disconnect() {
				webSocket.close();
			}
		}
	</script>
</body>
</html>